<template>
	<div 
		id="_editor"
		class="_editor" 
		ref="_editor" 
		contenteditable="true"
		spellcheck = "false"
		@keyup="eventFunc"
		@keydown="eventFunc"
		@click="eventFunc"
		@keydown.enter.prevent="submit"
		@focus="focus"
		@blur="blur">
		<!-- @paste.prevent="onPaste" -->
	</div>
</template>
<script>
	export default {
		data () {
		  return {
			editor:null,
			sel:null,
			ran:null,
		  }
		},
		mounted () {
			this.editor = this.$refs['_editor'];
			this.editor.focus();
			this.setRange();
			this.editor.blur();
			window.scrollTo(0, 0);
			this.defaultFunc();
			this.filter();
		},
		methods: {
			eventFunc() {
				var self = this;
				var obj = this.editor;
				var oText = obj.textContent;
				var oHtml = obj.innerHTML;
				var oTLen = oText.length;
				var oHLen = oHtml.length;
				if(oTLen == 0 && oHLen != 0) {
					if(oHLen == 4) {
						var br = obj.getElementsByTagName('br');
						self.removeElement(br[br.length - 1]);
					} else if(oHLen == 11 || oHLen == 13) {
						var p = obj.getElementsByTagName('p');
						self.removeElement(p[p.length - 1]);
					} else if(oHLen == 15) {
						var div = obj.getElementsByTagName('div');
						self.removeElement(div[div.length - 1]);
					}
				}
				if(document.activeElement.id = obj.id) self.setRange();
			},
			insertHTML(html) {
				if(this.ran == undefined) {
					this.editor.focus();
					this.setRange();
				}
				var oFragment = this.ran.createContextualFragment(html);
				var oLastNode = oFragment.lastChild;
				this.ran.deleteContents();
				this.ran.insertNode(oFragment);
				this.ran.setStartAfter(oLastNode);
				this.sel.removeAllRanges();
				this.sel.addRange(this.ran);
				this.editor.focus();
			},
			/*
			 	src; 图片路径
			 	remark; 图片文字描述
			 	afterInsert; 插入后回调
			 * */
			insertEmoji({src,remark = '',afterInsert}) {
				if(src == undefined){
					console.error('insert emoji src is not define');
					return false;
				}
				var newImg = '<img src="' + src + '"remark="' + remark + '" />';
				this.insertHTML(newImg);
				if(afterInsert) {
					afterInsert.call(this);
				}
				//return this;
			},
			/*
				text; 插入文字
				color; 文字颜色
				afterInsert; 插入后毁掉函数
			 * */
			insertBlock({text,color = '#000',remark = '',afterInsert}) {
				this.insertHTML('<br id="changeLinear"/><span id="easyEditorSaveWidth">' + text + '</span>');
				var spanObj = document.getElementById('easyEditorSaveWidth');
				var width = this.getRect(spanObj).width;
				this.removeElement(spanObj);
				this.removeElement(document.getElementById('changeLinear'));
				var labelBox = '<input type="text" disabled="disabled" value="' + text + '" remark="' + remark + '" style="width:' + width + 'px;color:' + color + ';">';
				this.insertHTML(labelBox);
				if(afterInsert) {
					afterInsert.call(this);
				}
				//return this;
			},
			setRange() {
				this.sel = this.createRange();
				if(this.sel == null) {
					return false
				} else {
					(window.getSelection) ? this.ran = this.sel.getRangeAt(0): this.ran = this.sel.createRange();
				}
			},
			createRange() {
				if(window.getSelection) {
					var sel = window.getSelection();
					if(sel.rangeCount > 0) {
						return sel;
					}
				} else if(document.selection) {
					var sel = document.selection;
					return sel.createRange();
				}
				return null;
			},
			defaultFunc() {
				if((typeof Range !== "undefined") && !Range.prototype.createContextualFragment) {
					Range.prototype.createContextualFragment = function(html) {
						var frag = document.createDocumentFragment(),
							div = document.createElement("div");
						frag.appendChild(div);
						div.outerHTML = html;
						return frag;
					};
				}
			},
			filter() {
				var self = this;
				try {
					document.execCommand("AutoUrlDetect", false, false);
				} catch(e) {}
			},
			removeElement(_element) {
				var _parentElement = _element.parentNode;
				if(_parentElement) {
					_parentElement.removeChild(_element);
				}
			},
			getRect(el) {
				var rect = el.getBoundingClientRect();
				var _left = document.documentElement.clientLeft;
				var _top = document.documentElement.clientTop;
				return {
					left: rect.left - _left,
					top: rect.top - _top,
					right: rect.right - _left,
					bottom: rect.bottom - _top,
					width: rect.right - rect.left,
					height: rect.bottom - rect.top
				}
			},
			submit(){
				this.$emit('submit', this.editor)
			},
			focus(){
				this.$emit('focus', this.editor)
			},
			blur(){
				this.$emit('blur', this.editor)
			},
			getContent(bol) {
				var oldHtml = this.editor.innerHTML;
				if(typeof bol == 'function') {
					var func = bol;
					var bol = false;
				}
				var res = this.editor.innerHTML;
				if(bol) {
					var block = this.editor.getElementsByTagName('input');
					for(var i=0;i<block.length;i++){
						var newSpan = document.createElement('span');
						newSpan.innerHTML = block[i].getAttribute('value') + '-' + block[i].getAttribute('remark') + ']';
						block[i].parentNode.insertBefore(newSpan,block[i]);
					}
					var emojis = this.editor.getElementsByTagName('img');
					for(var i=0;i<emojis.length;i++){
						var newSpan = document.createElement('span');
						newSpan.innerHTML = emojis[i].getAttribute('remark');
						emojis[i].parentNode.insertBefore(newSpan,emojis[i]);
					}
					res = this.editor.innerHTML;
					res = res.replace(/<\/p>/g,'#easyEditor#');
					res = res.replace(/<\/div>/g,'#easyEditor#');
					res = res.replace(/<\/?[^>]*>/g,'');
					res = res.replace(/#easyEditor#/g,'<br />');
				}
				this.editor.innerHTML = oldHtml;
				return res;
			},
			//正则转换
			htmlEncode(strHTML){
				var strTem = "";
				if(strHTML.length == 0) return "";
				strTem = strHTML.replace(/&/g, "&gt;");
				strTem = strTem.replace(/</g, "&lt;");
				strTem = strTem.replace(/>/g, "&gt;");
				strTem = strTem.replace(/ /g, "&nbsp;");
				strTem = strTem.replace(/\'/g, "&#39;");
				strTem = strTem.replace(/\"/g, "&quot;");
				strTem = strTem.replace(/\n/g, "");
				return strTem;
			}
		}
	}
</script>

<style>
	._editor{
		overflow-y:auto;
		width:100%;
		height:56px;
		padding-left: 12px;
	}
	._editor img{
		width: 24px;
		height: 24px;
		cursor: default;
		margin: 0 1px;
	}
	._editor input{
		margin: 0 1px;
		cursor: default;
		background: transparent;
		border: 0px;
	}
	[contenteditable]:focus{outline: none;}
	/*滚动条样式*/
	._editor::-webkit-scrollbar {/*滚动条整体样式*/
		/*高宽分别对应横竖滚动条的尺寸*/
		width: 8px;
		background-color: rgba(0, 0, 0, 0);
	}
	._editor::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
	    border-radius: 4px;
	    background: #CDD2CC;
	}
	._editor::-webkit-scrollbar-track {/*滚动条里面轨道*/
	    border-radius: 0;
	    background: rgba(0,0,0,0);
	}
</style>
